<?php
/**
 * 现金卡类
 * @package  htdocs
 * @subpackage  module/company
 * @author   create by allen.qiang
 * @version 1.0
 */

class cardMaster{

    /**
     *现金卡查询
     */

    public function search( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        //现金卡id
        if (isset($arg_array['card_id']) && quanli_is_int($arg_array['card_id'])) {
            $sql .= ' AND cm.card_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_id'];
        }
        //现金卡名称
        if (isset($arg_array['card_name']) && !empty($arg_array['card_name'])) {
            $sql .= ' AND cm.card_name LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['card_name']) . '%';
        }

        //现金卡面值
        if (isset($_REQUEST['face_value_id']) && trim($_REQUEST['face_value_id']) != '') {
            $sql .= ' AND cm.face_value_id = ?';
            $params_type .= 'i';
            $params_array[] = $_REQUEST['face_value_id'];
        }

        //现金卡生产数量
        if (isset($arg_array['card_product_number']) && !empty($arg_array['card_product_number'])) {
            $sql .= ' AND cm.card_product_number = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_product_number'];
        }

        //可以使用次数
        if (isset($arg_array['can_use_number']) && !empty($arg_array['can_use_number'])) {
            $sql .= ' AND cm.can_use_number = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['can_use_number'];
        }

        //现金卡规格
        if (isset($arg_array['card_spec']) && !empty($arg_array['card_spec'])) {
            $sql .= ' AND cm.card_spec = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['card_spec'];
        }

        //代金卡生产状态
        if ( isset($arg_array['card_status']) && in_array( $arg_array['card_status'] , array(1,2,3,4) ) ) {
            $sql .= ' AND cm.card_status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_status'];
        }


        //有效期开始日期
        if (isset($_REQUEST['startDate']) && trim($_REQUEST['startDate']) != '' ) {
            $sql .= ' AND cm.startDate >= ?';
            $params_type .= 's';
            $params_array[] = trim($_REQUEST['startDate']);
        }
        //有效期结束日期
        if (isset($_REQUEST['endDate']) && trim($_REQUEST['endDate']) != '') {
            $sql .= ' AND cm.endDate <= ?';
            $params_type .= 's';
            $params_array[] = trim($_REQUEST['endDate']);
        }

        //卡系统卡类型
        if (isset($_REQUEST['card_type']) && is_numeric($_REQUEST['card_type'])) {
            $sql .= ' AND cm.card_type = ?';
            $params_type .= 'i';
            $params_array[] = $_REQUEST['card_type'];
        }

        //备注
        if (isset($arg_array['remark']) && !empty($arg_array['remark'])) {
            $sql .= ' AND cm.remark = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['remark'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count
                        FROM card_master cm
                        INNER JOIN  goods_selector gs ON gs.selectID = cm.goods_selector_id
                       ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT cm.createTime,cm.card_id,cm.card_warehouse_voucher_number,cm.card_spec,cm.card_name,cm.face_value,cm.card_spec_id,cm.face_value_id,cm.card_product_number,cm.card_status,cm.can_use_number,cm.startDate,cm.endDate,cm.card_type,cm.goods_selector_id,cm.remark,gs.selectID,gs.selectName
                        FROM card_master cm
                        INNER JOIN  goods_selector gs ON gs.selectID = cm.goods_selector_id
                       ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'creator'     	=> $item->creator,
                    'createTime'  	=> $item->createTime,
                    'card_id'     => $item->card_id,
                    'card_name'   => $item->card_name,
                    'face_value_id'   => $item->face_value_id,
                    'face_value'   => $item->face_value,
                    'card_product_number'    	=> $item->card_product_number,
                    'can_use_number'  => $item->can_use_number,
                    'card_status'    	=> $item->card_status,
                    'startDate'       	=> $item->startDate,
                    'endDate'       	=> $item->endDate,
                    'card_type'       	=> $item->card_type,
                    'goods_selector_id'       	=> $item->goods_selector_id,
                    'remark'       	=> $item->remark,
                    'selectName'=>$item->selectName,
                    'card_spec_id'       	=> $item->card_spec_id,
                    'card_spec'       	=> $item->card_spec,
                    'card_warehouse_voucher_number'    => $item->card_warehouse_voucher_number
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 添加、修改现金卡
     *
     */
    public function editCard ( $arg_array ) {

        global $G_SHOP;

        quanli_require('module/base/company/cardFaceValue.class.php');

        $cardFaceValue = new cardFaceValue();//实例化现金卡面值类

        //检查参数

        if (!isset( $arg_array['card_name'],$arg_array['goods_selector_id'],$arg_array['card_product_number'],$arg_array['can_use_number'],$arg_array['startDate'],$arg_array['endDate'],$arg_array['card_type'],$arg_array['cityID'],$arg_array['card_spec_id']) && !is_numeric($arg_array['card_id'])){
            return array('message'=>'参数错误','code'=> 400);
        }

        if (empty($arg_array['card_name']))
            return array( 'code' => 400, 'message' => '请填写现金卡名称' );

        if (empty($arg_array['card_product_number']))
            return array( 'code' => 400, 'message' => '请填写现金卡数量' );

        if (empty($arg_array['can_use_number'])){
            return array( 'code' => 400, 'message' => '请填写可使用次数' );
        }

        if ($arg_array['card_type'] <= 0)
            return array( 'code' => 400, 'message' => '请选卡系统卡类型' );

        if (empty($arg_array['startDate']))
            return array( 'code' => 400, 'message' => '请填写有效开始日期' );

        if (empty($arg_array['card_type']))
            return array( 'code' => 400, 'message' => '请填写有效结束日期' );

        if (empty($arg_array['goods_selector_id']))
            return array( 'code' => 400, 'message' => '请选择商品筛选器' );

        if (empty($arg_array['cityID']))
            return array( 'code' => 400, 'message' => '请选择城市' );

        if (empty($arg_array['card_spec_id']))
            return array( 'code' => 400, 'message' => '请选择现金卡规格' );


        $creator                          = $arg_array['creator'];
        $card_id                          = $arg_array['card_id'] ;
        $card_name                        = $arg_array['card_name'] ;
        $face_value_id	                  = $arg_array['face_value_id'] ;
        $card_product_number              = $arg_array['card_product_number'] ;
        $can_use_number                   = $arg_array['can_use_number'] ;
        $startDate                        = $arg_array['startDate'] ;
        $endDate                          = $arg_array['endDate'] ;
        $card_type                        = $arg_array['card_type'] ;
        $remark                           = $arg_array['remark'] ;
        $goods_selector_id	              = $arg_array['goods_selector_id'] ;
        $cityID	                          = $arg_array['cityID'] ;
        $card_spec_id	                  = $arg_array['card_spec_id'] ;
        $card_spec	                      = $arg_array['card_spec'] ;

        try{

            // 查询现金卡面值信息
            $search_args_array = array(
                'face_value_id' => $face_value_id
            );
            $card_array = $cardFaceValue->search( $search_args_array );

            $card_master = new entity('card_master') ;
            if ($card_id == 0) {
                $card_master->creator = $creator;
                $card_master->card_id = generate_seqno('seqno_card');
            } else {
                $card_master->card_id = $card_id;
                $delete_sql = 'DELETE FROM card_city WHERE card_id = ? ';
                $G_SHOP->DBCA->stmt_query($delete_sql, 'i', $card_id);
                if (!$G_SHOP->DBCA->fetch($card_master)) {
                    throw new Exception('现金卡信息没有找到', 404);
                }
            }

            //保存现金卡信息
            $card_master->card_name = $card_name;
            $card_master->face_value_id = $face_value_id;
            $card_master->card_product_number = $card_product_number;
            $card_master->can_use_number = $can_use_number;
            $card_master->card_status = 1;
            $card_master->startDate = $startDate;
            $card_master->endDate = $endDate;
            $card_master->card_type = $card_type;
            $card_master->remark = $remark;
            $card_master->goods_selector_id = $goods_selector_id;
            $card_master->card_spec_id = $card_spec_id;
            $card_master->card_spec = $card_spec;
            $card_master->face_value = $card_array[0]['face_value'];
            $G_SHOP->DBCA->save( $card_master ) ;


            foreach($cityID as $key => $city){
                $city_master = new entity('card_city') ;
                $city_master->creator = $creator;
                $city_master->card_id = $card_master->card_id;
                $city_master->cityID = $city;
                //获取城市信息
                $city_array = $G_SHOP->getCache('city');                                        //读取缓存城市数据
                foreach($city_array as $city_name){

                    if($city == $city_name['id']){
                        $city_master->cityName = $city_name['name'];
                    }
                }

                $G_SHOP->DBCA->save( $city_master ) ;
            }

            if ($card_id > 0) {
                return array( 'code' => 200, 'message' => '现金卡修改成功' );
            } else {
                return array( 'code' => 200, 'message' => '现金卡保存成功' );
            }

        }catch (Exception $e) {
            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
    }

    /**
     * 删除现金卡
     * @param array $pay_array 现金卡ID
     * @return array
     */
    public function deleteCard ( $pay_array ) {

        global $G_SHOP;

        if (!isset($pay_array) || empty($pay_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            //=================start删除现金卡信息表card_master=======================
            $card_master_obj = new entity( 'card_master' );
            $card_master_obj->card_id = $pay_array['card_id'];
            if ( !$G_SHOP->DBCA->fetch( $card_master_obj ) ) {
                returnJsonData('现金卡信息没有找到', 404);
            }
            $G_SHOP->DBCA->delete( $card_master_obj );
            //=================end删除现金卡信息表card_master=======================


            //=================start删除现金卡信息表card_city=======================
            $card_city_obj = new entity( 'card_city' );
            $card_city_obj->card_id = $pay_array['card_id'];
            if ( !$G_SHOP->DBCA->fetch( $card_city_obj ) ) {
                returnJsonData('现金卡城市信息没有找到', 404);
            }
            $G_SHOP->DBCA->delete( $card_city_obj );
            //=================end删除现金卡信息表card_city=======================

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '删除现金卡成功' );


        } catch ( Exception $e ) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 审核卡生产单
     * @param int $card_id 生产单ID
     * @return array
     * @throws Exception
     */
    public function auditCardProduct( $card_id ) {

        global $G_SHOP;

        if( !is_numeric($card_id) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        /**
         * 现金卡生产单状态：1:待审核   2：已审核   3:已生产   4:已入库
         */

        try{
            $G_SHOP->DBCA->beginTransaction();

            //查询生产单信息
            $card_master = new entity('card_master');

            $card_master->card_id = $card_id;

            if( !$G_SHOP->DBCA->fetch( $card_master ) )

                throw new Exception('没有找到现金卡信息',404  );

            if( $card_master->card_status != 1 )

                throw new Exception('您当前页面已过期，请刷新页面',404  );

            $card_master->card_status = 2;

            $G_SHOP->DBCA->save($card_master);

            $G_SHOP->DBCA->commit();
            return array( 'code' => 200, 'message' => '审核成功' );

        }catch (Exception $e){
            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0){
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            }else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }

    }

    /**
     * 生产现金卡
     * @param int $card_id 代金卡单号ID
     * @return array
     */
    public function createCardCode( $card_id ) {

        global $G_SHOP;

        if (!isset($card_id) || !is_numeric($card_id)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            //判断代金卡是否存在
            $card_master = new entity('card_master');
            $card_master->card_id = $card_id;
            if ( !$G_SHOP->DBCA->fetch($card_master) ) {
                throw new Exception('现金卡信息没有找到', 404);
            }
            if ($card_master->card_status == 1) {
                throw new Exception('现金卡未审核', 404);
            }
            if ($card_master->card_status == 3) {
                throw new Exception('现金卡已生产', 404);
            }
            if ($card_master->card_status == 4) {
                throw new Exception('现金卡已入库', 404);
            }

            //一次生产的现金卡数量
            $num = 1000;

            //循环生生产次数
            $times = ceil( $card_master->card_product_number / $num );
            if ($times == 0) {
                $times = 1;
            }

            //生产代金卡
            $i = 0;

            $already_product_num = 0;

            while($i < $times) {

                //最后一次循环
                if($i == $times -1 ){
                    $num = $card_master->card_product_number - $already_product_num;
                }

                $sql = 'INSERT INTO card_detail(uuid,timeStamp,creator,createTime,card_id,card_no,card_name,card_pwd,warehouse_voucher_id,
                        apply_id,card_type,face_value_id,face_value,discount,card_status,can_use_number,used_number,good_selector_id,
                        send_card_time,startDate,endDate) VALUES ';

                for($j = 0; $j < $num; $j++) {

                    $card_no = generate_seqno('seqno_card_no');

                    $card_pwd = encryptD(get_random_string(15, 'number'));

                    if ($j == 0) {
                        $sql .= sprintf('("%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s")',
                            make_uuid(), $G_SHOP->sys_datetime, 'system__publish', $G_SHOP->sys_datetime,$card_master->card_id, $card_no,
                            $card_master->card_name, $card_pwd, $card_master->warehouse_voucher_id, $card_master->apply_id,
                            $card_master->card_type, $card_master->face_value_id, $card_master->face_value, $card_master->discount,
                            1, $card_master->can_use_number, $card_master->used_number,$card_master->goods_selector_id,
                            $card_master->send_card_time, $card_master->startDate, $card_master->endDate);
                    } else {
                        $sql .= sprintf(',("%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s")',
                            make_uuid(), $G_SHOP->sys_datetime, 'system__publish', $G_SHOP->sys_datetime,$card_master->card_id, $card_no,
                            $card_master->card_name, $card_pwd, $card_master->warehouse_voucher_id, $card_master->apply_id,
                            $card_master->card_type, $card_master->face_value_id, $card_master->face_value, $card_master->discount,
                            1, $card_master->can_use_number, $card_master->used_number,$card_master->goods_selector_id,
                            $card_master->send_card_time, $card_master->startDate, $card_master->endDate);
                    }

                }

                if ($G_SHOP->DBCA->execute($sql)) {
                    ++$i;
                    $already_product_num += $num;
                }

            }

            $card_master->card_status = 3;
            $G_SHOP->DBCA->save( $card_master );

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '现金卡生产成功' );

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }

    /**
     * 现金卡信息入库类
     *
     */

    public function searchcardWarehouseVoucher( &$arg_array ){

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //现金卡id
        if ( isset($arg_array['card_id']) && is_numeric($arg_array['card_id']) ) {
            $sql .= ' AND card_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_id'];
        }

        //入库单id
        if ( isset($arg_array['warehouse_voucher_id']) && is_numeric($arg_array['warehouse_voucher_id']) ) {
            $sql .= ' AND warehouse_voucher_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['warehouse_voucher_id'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_warehouse_voucher ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询现金卡入库单信息
            $search_sql = 'SELECT * FROM card_warehouse_voucher ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'uuid'  => $item->uuid,
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'apply_id' => $item->card_id,
                    'warehouse_voucher_id' => $item->warehouse_voucher_id,
                    'face_value_id' => $item->face_value_id,
                    'face_value' => $item->face_value,
                    'card_spec_id' => $item->card_spec_id,
                    'card_spec' => $item->card_spec,
                    'card_no_start' => $item->card_no_start,
                    'card_no_end' => $item->card_no_end,
                    'card_warehouse_voucher_number' => $item->card_warehouse_voucher_number,
                    'remark' => $item->remark

                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 现金卡入库
     * @param int $card_id 现金卡ID
     * @return array
     * @throws Exception
     */
    public function warehouseCard( $args_array ) {

        global $G_SHOP;

        quanli_include('module/base/company/cardDetail.class.php');

        if (!isset($args_array['card_id']) || !is_numeric( $args_array['card_id'] )) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!isset($args_array['card_detail']) || !is_array($args_array['card_detail']) || empty($args_array['card_detail'])) {
            return array( 'code' => 400 , 'message' => '请录入现金卡' );
        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            //判断现金卡信息，并修改现金卡状态
            $card_master = new entity('card_master');
            $card_master->card_id = $args_array['card_id'];

            if ( !$G_SHOP->DBCA->fetch($card_master) ) {
                throw new Exception('现金卡信息没有找到', 404);
            }

            if ( $card_master->card_status == 1 ) {
                throw new Exception('此申领单未审核', 404);
            }
            if ( $card_master->card_status == 4) {
                throw new Exception('此申领单已入库', 404);
            }

            foreach($args_array['card_detail'] as $data){
                $card_no_start = $data['card_no_start'];
                $card_no_end = $data['card_no_end'];

                $card_master->card_warehouse_voucher_number =$card_master->card_warehouse_voucher_number + $card_no_end - $card_no_start + 1;

                if ($card_master->card_warehouse_voucher_number == $card_master->card_product_number) {
                    $card_master->card_status = 4;
                }
            }



            $G_SHOP->DBCA->save( $card_master );

            //保存现金卡入库信息
            foreach($args_array['card_detail'] as $data){
                $card_warehouse_voucher = new entity('card_warehouse_voucher');
                $card_warehouse_voucher->card_id = $args_array['card_id'];
                $card_warehouse_voucher->warehouse_voucher_id = "RK".generate_seqno('seqno_warehouse_voucher');
                $card_warehouse_voucher->creator = $args_array['operator'];
                $card_warehouse_voucher->face_value_id = $card_master->face_value_id;
                $card_warehouse_voucher->face_value = $card_master->face_value;
                $card_warehouse_voucher->card_spec_id = $card_master->card_spec_id;
                $card_warehouse_voucher->card_spec = $card_master->card_spec;
                $card_warehouse_voucher->remark = $card_master->remark;
                $card_warehouse_voucher->card_no_start = $data['card_no_start'];
                $card_warehouse_voucher->card_no_end = $data['card_no_end'];
                $card_warehouse_voucher->card_warehouse_voucher_number = $card_warehouse_voucher->card_no_end - $card_warehouse_voucher->card_no_start + 1;
                $G_SHOP->DBCA->save($card_warehouse_voucher);

                //更新现金卡状态
                $G_SHOP->DBCA->stmt_query('UPDATE card_detail SET card_status = 3, warehouse_voucher_id = ? WHERE card_no BETWEEN ? AND ?',
                    'sss', $card_warehouse_voucher->warehouse_voucher_id, $data['card_no_start'], $data['card_no_end']);
            }




            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '现金卡入库成功' );

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }

    /**
     * 现金卡信息调拨类
     *
     */

    public function searchCardAllot( &$arg_array ){

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //现金卡id
        if ( isset($arg_array['card_id']) && is_numeric($arg_array['card_id']) ) {
            $sql .= ' AND card_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_id'];
        }

        //入库调拨id
        if ( isset($arg_array['allot_id']) && is_numeric($arg_array['allot_id']) ) {
            $sql .= ' AND allot_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['allot_id'];
        }

        if ( isset($arg_array['extend_sql']) && !empty($arg_array['extend_sql']) ) {
            $sql .= $arg_array['extend_sql'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_allot ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询现金卡入库单信息
            $search_sql = 'SELECT * FROM card_allot ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'uuid'  => $item->uuid,
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'apply_id' => $item->card_id,
                    'allot_id' => $item->allot_id,
                    'face_value_id' => $item->face_value_id,
                    'face_value' => $item->face_value,
                    'card_spec_id' => $item->card_spec_id,
                    'card_spec' => $item->card_spec,
                    'card_no_start' => $item->card_no_start,
                    'card_no_end' => $item->card_no_end,
                    'card_product_number' => $item->card_product_number,
                    'office_id' => $item->office_id,
                    'office_name' => $item->office_name,
                    'remark' => $item->remark

                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 现金卡调拨
     * @param int $card_id 现金卡ID
     * @return array
     * @throws Exception
     */
    public function cardAllot( $args_array ) {

//        echo "<pre>";
//        print_r($args_array);die;


        global $G_SHOP;

        quanli_include('module/base/company/cardDetail.class.php');

        if (!isset($args_array['card_id']) || !is_numeric( $args_array['card_id'] )) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!isset($args_array['card_detail']) || !is_array($args_array['card_detail']) || empty($args_array['card_detail'])) {
            return array( 'code' => 400 , 'message' => '请录入现金卡' );
        }

//        if (!isset($args_array['office_id']) || !is_array($args_array['office_id']) || empty($args_array['office_id'])) {
//            return array( 'code' => 400 , 'message' => '请选择调入办公室' );
//        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            //判断现金卡信息，并修改现金卡状态
            $card_master = new entity('card_master');
            $card_master->card_id = $args_array['card_id'];
            if ( !$G_SHOP->DBCA->fetch($card_master) ) {
                throw new Exception('现金卡信息没有找到', 404);
            }

            $G_SHOP->DBCA->save( $card_master );

            //保存现金卡入库信息
            foreach($args_array['card_detail'] as $data){
                $card_allot = new entity('card_allot');
                $card_allot->card_id = $args_array['card_id'];
                $card_allot->allot_id = generate_seqno('seqno_alloat');
                $card_allot->creator = $args_array['operator'];
                $card_allot->face_value_id = $card_master->face_value_id;
                $card_allot->face_value = $card_master->face_value;
                $card_allot->card_spec_id = $card_master->card_spec_id;
                $card_allot->card_spec = $card_master->card_spec;
                $card_allot->remark = $card_master->remark;
                $card_allot->card_no_start = $data['card_no_start'];
                $card_allot->card_no_end = $data['card_no_end'];
                $card_allot->office_id = $data['office_id'];
                $card_allot->office_name = $data['office_name'];
                $card_allot->card_product_number = $card_allot->card_no_end - $card_allot->card_no_start + 1;

                $G_SHOP->DBCA->save($card_allot);

                /*=======================================================
                  * 写入日志 start
                  * ======================================================
                */
                quanli_include('module/base/customer/logHandler.class.php');
                //实例日志类
                $logHandler = new logHandler( $G_SHOP->DBCA );

                $log_array = array(
                    'logCategoryID' => 10,
                    'logItem' => $card_allot->allot_id,
                    'extend_1' => '现金卡调拨',
                    'extend_2' => '调拨现金卡' . $card_allot->card_no_start.'~'.$card_allot->card_no_end .'共'.$card_allot->card_product_number.'张，调拨给'.$card_allot->office_name,
                    'operator' => $G_SHOP->currentUserID
                );

                $logHandler->saveLogInfo( $log_array );
                /*=======================================================
                 * 写入日志 end
                 * ======================================================
                 */
            }

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '现金卡调拨成功' );

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }

}
